package com.xuzz.study.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioServer {
    public static void main(String[] args) throws Exception
    {
        /**
         * 可用telnet来测试
         * telnet 127.0.0.1 6666
         * ctrl+] 进入
         *
         * send 要发送的消息
         * send 要发送的消息
         */
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("server started");
        while(true)
        {
            final Socket acceptedSocket = serverSocket.accept();
            System.out.println("接到一个客户端");
            newCachedThreadPool.execute(()->{
                handle(acceptedSocket);
            });
        }
    }

    public static void  handle(Socket clienSocket)
    {
        try
        {
            System.out.println("当前线程id="+Thread.currentThread().getId()+",name="+Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            InputStream in = clienSocket.getInputStream();

            while(true)
            {
                System.out.println("当前线程id="+Thread.currentThread().getId()+",name="+Thread.currentThread().getName());
                int readed = in.read(bytes);
                if(readed==-1)
                {
                    break;
                }
                System.out.println("输出客户端发送的数据");
                System.out.println(new String(bytes,0,readed));
            }
        }catch (IOException e)
        {
            e.printStackTrace();
        }
        finally {
            System.out.println("关闭客户端连接");
            try {
                clienSocket.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
